package com.isoftstone.wms.common;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;

/**
 * 数据库重置工具类
 */
@Component
public class DatabaseResetUtil {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 重置menu表的自增ID从指定值开始
     * @param startId 起始ID
     */
    public void resetMenuAutoIncrement(int startId) {
        try {
            String sql = "ALTER TABLE menu AUTO_INCREMENT = ?";
            jdbcTemplate.update(sql, startId);
            System.out.println("Menu表自增ID已重置为从 " + startId + " 开始");
        } catch (Exception e) {
            System.err.println("重置自增ID失败: " + e.getMessage());
        }
    }

    /**
     * 查看menu表的当前状态
     */
    public void showMenuStatus() {
        try {
            // 查看当前数据
            String selectSql = "SELECT * FROM menu ORDER BY id";
            List<Map<String, Object>> menus = jdbcTemplate.queryForList(selectSql);
            
            System.out.println("当前menu表数据:");
            for (Map<String, Object> menu : menus) {
                System.out.println("ID: " + menu.get("id") + 
                                 ", 名称: " + menu.get("menuName") + 
                                 ", 编码: " + menu.get("menuCode"));
            }
            
            // 查看自增ID状态
            String statusSql = "SHOW TABLE STATUS LIKE 'menu'";
            List<Map<String, Object>> status = jdbcTemplate.queryForList(statusSql);
            if (!status.isEmpty()) {
                Map<String, Object> tableStatus = status.get(0);
                System.out.println("当前自增ID: " + tableStatus.get("Auto_increment"));
            }
        } catch (Exception e) {
            System.err.println("查看状态失败: " + e.getMessage());
        }
    }

    /**
     * 清空menu表并重置自增ID
     * 注意：这会删除所有现有数据！
     */
    public void clearMenuTableAndReset(int startId) {
        try {
            // 清空表
            jdbcTemplate.update("DELETE FROM menu");
            System.out.println("Menu表数据已清空");
            
            // 重置自增ID
            resetMenuAutoIncrement(startId);
            
            System.out.println("Menu表已重置，自增ID从 " + startId + " 开始");
        } catch (Exception e) {
            System.err.println("清空并重置失败: " + e.getMessage());
        }
    }
}
